package vashion.azeroth.core.manager.item;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;

import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.contant.GenericErrorEnum;
import vashion.azeroth.contant.ItemErrorEnum;
import vashion.azeroth.contant.TagErrorEnum;
import vashion.azeroth.core.common.NeedOperateFlow;
import vashion.azeroth.core.dao.BaseDao;
import vashion.azeroth.core.item.dao.ItemTagDao;
import vashion.azeroth.core.item.pojo.ForestDO;
import vashion.azeroth.core.item.pojo.ItemBrandDO;
import vashion.azeroth.core.item.pojo.ItemDO;
import vashion.azeroth.core.item.pojo.ItemTagDO;
import vashion.azeroth.core.item.pojo.TagDO;
import vashion.azeroth.core.manager.forest.BaseForestManager;
import vashion.azeroth.core.manager.impl.BaseManagerImpl;
import vashion.azeroth.core.pojo.common.OperateFlowEnum;
import vashion.azeroth.core.result.ApiResult;

/**
 * @author Reganchen on 17/7/17. 商品和标签关联管理
 */
@Service
public class ItemTagManager extends BaseManagerImpl<ItemTagDO> {

	private static final String ITEM_FEMALE = "女";

	private static final String ITEM_MALE = "男";

	private static final String ITEM_ALL = "通用";

	private final static Logger log = LoggerFactory.getLogger(ItemTagManager.class);

	@Autowired
	private ItemTagDao itemTagDao;

	@Autowired
	private TagManager tagManager;

	@Autowired
	private BaseItemManager baseItemManager;

	@Autowired
	private BaseItemBrandManager baseItemBrandManager;

	@Autowired
	private BaseForestManager baseForestManager;

	@Autowired
	private ItemWriteManager itemWriteManager;

	@Override
	public BaseDao<ItemTagDO> getDao() {
		return itemTagDao;
	}

	/**
	 * 查询某商品的标签
	 * 
	 * @param itemId
	 * @return 此商品的所有标签
	 */
	public ApiResult<List<ItemTagDO>> findByItemId(long itemId) {
		try {
			ItemTagDO itemTagDO = new ItemTagDO();
			itemTagDO.setItemId(itemId);
			itemTagDO.setStatus(AzerothConstants.ItemTag.NORMAL);
			List<ItemTagDO> itemTagList = itemTagDao.find(itemTagDO);
			//如果标签没有名字，进行查找
			for (ItemTagDO itemTagDOTemp : itemTagList) {
				if (null == itemTagDOTemp.getTagTitle()) {
					TagDO tagDOTemp = tagManager.get(itemTagDOTemp.getTagId());
					if (null != tagDOTemp) {
						itemTagDOTemp.setTagTitle(tagDOTemp.getTitle());
					}
				}
			}
			return ApiResult.newSuccessResult(itemTagList);
		} catch (Exception e) {
			return ApiResult.newErrorResult(GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
	}

	/**
	 * 给商品添加标签
	 * 
	 * @param itemId
	 * @param tagTitle
	 * @param operatorId
	 * @return 添加是否成功
	 */
	@NeedOperateFlow(operateIdArgLocation = 2, operateFlowEnum = OperateFlowEnum.TAG)
	public ApiResult<Boolean> addTagForItem(long itemId, String tagTitle, Long operatorId) {
		try {
			// 查询商品是否存在
			ItemDO itemDO = baseItemManager.get(itemId);
			if (null == itemDO) {
				return ApiResult.newErrorResult(ItemErrorEnum.NOT_EXITS.getErrorCode(),
						ItemErrorEnum.NOT_EXITS.getErrorMessage());
			}
			// 按照名字查找Tag，如果不存在，保存新的
			ApiResult<List<TagDO>> tagResult = tagManager.findByExactTagTitle(tagTitle);
			ItemTagDO itemTagDO = new ItemTagDO();
			if (tagResult.isSuccess()) {
				if (CollectionUtils.isEmpty(tagResult.getData())) {
					// 保存新的Tag
					ApiResult<Long> saveTagResult = tagManager.publishTag(tagTitle, operatorId);
					if (!saveTagResult.isSuccess() || null == saveTagResult.getData()) {
						return ApiResult.newErrorResult(GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
								GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
					}
					long tagId = saveTagResult.getData();
					itemTagDO.setTagId(tagId);
				} else {
					// 设置原有的Tag的ID
					TagDO tagDo = tagResult.getData().get(0);
					itemTagDO.setTagId(tagDo.getId());
				}
			} else {
				return ApiResult.newErrorResult(tagResult.getErrorCode(), tagResult.getErrorMsg());
			}
			itemTagDO.setItemId(itemId);
			itemTagDO.setStatus(AzerothConstants.ItemTag.NORMAL);
			itemTagDO.setOperatorId(operatorId);
			// 查询商品是否已有此标签，如果没有，保存关联
			List<ItemTagDO> itemTagDOList = itemTagDao.find(itemTagDO);
			if (CollectionUtils.isEmpty(itemTagDOList)) {
				itemTagDO.setTagTitle(tagTitle);
				itemTagDao.save(itemTagDO);
				//更新商品特殊修改时间
				ItemDO itemDOUpdate = new ItemDO();
				itemDOUpdate.setSpecialGmtModified(new Date());
				itemWriteManager.updateItem(itemDOUpdate, null, operatorId);
			} else {
				return ApiResult.newErrorResult(TagErrorEnum.ALREADY_CONNECT.getErrorCode(),
						TagErrorEnum.ALREADY_CONNECT.getErrorMessage());
			}
			return ApiResult.newSuccessResult(true);
		} catch (Exception e) {
			return ApiResult.newErrorResult(GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}

	}

	/**
	 * 为商品添加默认的标签，取自品牌、类目、适用人群
	 * 
	 * @param itemDO
	 * @param operatorId
	 * @return 添加结果
	 */
	@NeedOperateFlow(operateIdArgLocation = 1, operateFlowEnum = OperateFlowEnum.TAG)
	public ApiResult<Boolean> addDefaultTagsForItem(ItemDO itemDO, Long operatorId) {

		// 设置品牌名为默认标签
		if (itemDO.getBrandId() > 0) {
			String brandTitle = itemDO.getBrandTitle();
			if (StringUtils.isBlank(brandTitle)) {
				ItemBrandDO itemBrandDO = baseItemBrandManager.get(itemDO.getBrandId());
				brandTitle = itemBrandDO.getTitle();
			}
			if (StringUtils.isNotBlank(brandTitle)) {
				addTagForItem(itemDO.getId(), brandTitle, operatorId);
			}
		}

		// 设置子类目和父类目名为默认标签
		ForestDO forest = baseForestManager.get(itemDO.getCategoryId());
		if (null != forest) {
			String forestTitle = forest.getTitle();
			if (StringUtils.isNotBlank(forestTitle)) {
				addTagForItem(itemDO.getId(), forestTitle, operatorId);
			}
			Long parentId = forest.getParentId();
			if (null != parentId && parentId > 0) {
				ForestDO parentForest = baseForestManager.get(parentId);
				if (null != parentForest && null != parentForest.getTitle()) {
					String parentForestTitle = parentForest.getTitle();
					if (StringUtils.isNotBlank(parentForestTitle)) {
						addTagForItem(itemDO.getId(), parentForestTitle, operatorId);
					}
				}
			}
		}

		// 设置适用人群为默认标签
		String feature = itemDO.getFeature();
		if (StringUtils.isNotBlank(feature)) {
			if (feature.equals(AzerothConstants.Item.ALL.toString())) {
				feature = ITEM_ALL;
			} else if (feature.equals(AzerothConstants.Item.MALE.toString())) {
				feature = ITEM_MALE;
			} else if (feature.equals(AzerothConstants.Item.FEMALE.toString())) {
				feature = ITEM_FEMALE;
			}
			addTagForItem(itemDO.getId(), feature, operatorId);
		}

		return ApiResult.newSuccessResult(true);
	}

	/**
	 * 给商品修改标签,可设置是否删除其他标签
	 * 
	 * @param itemId
	 * @param tagListString
	 * @param operatorId
	 * @param deleteOther
	 * @return 修改是否成功
	 */
	@NeedOperateFlow(operateIdArgLocation = 2, operateFlowEnum = OperateFlowEnum.TAG)
	public ApiResult<Boolean> updateTagsForItem(long itemId, String tagListString, Long operatorId, boolean deleteOther) {
		try {
			List<String> tagList = tagListString2TagList(tagListString);
			if (null == tagList)
				return ApiResult.newErrorResult(GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
						GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
			// 添加所有标签
			for (String tagTemp : tagList) {
				addTagForItem(itemId, tagTemp, operatorId);
			}

			// 如果设置需要删除其他标签，进行删除
			ItemTagDO itemTagDO = new ItemTagDO();
			itemTagDO.setItemId(itemId);
			itemTagDO.setStatus(AzerothConstants.ItemTag.NORMAL);
			List<ItemTagDO> itemTagList = itemTagDao.find(itemTagDO);
			List<ItemTagDO> itemTagList2Delete = Lists.newArrayList();
			for (ItemTagDO itemTagDOTemp : itemTagList) {
				TagDO tagDOTemp = tagManager.get(itemTagDOTemp.getTagId());
				if (!tagList.contains(tagDOTemp.getTitle().trim())) {
					itemTagList2Delete.add(itemTagDOTemp);
				}
			}
			for (ItemTagDO itemTagDOTemp : itemTagList2Delete) {
				itemTagDao.remove(itemTagDOTemp);
			}

		} catch (Exception e) {
			return ApiResult.newErrorResult(GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
		return ApiResult.newSuccessResult(true);
	}

	/**
	 * @param tagListString
	 */
	private List<String> tagListString2TagList(String tagListString) {
		if (StringUtils.isNotBlank(tagListString)) {
			String[] tagArray = tagListString.split(",");
			List<String> tagList = new ArrayList<String>();
			for (String tag : tagArray) {
				tagList.add(tag.trim());
			}
			if (!tagList.isEmpty()) {
				return tagList;
			}
		}
		return null;
	}
	

}
